package org.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.domain.parameter.UserParameter;
import org.example.domain.po.*;
import org.example.domain.query.UserQuery;
import org.example.domain.vo.ErpUserVO;
import org.example.service.*;
import org.example.mapper.ErpUserMapper;
import org.example.utils.Result;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
* @author DELL
* @description 针对表【erp_user(用户表)】的数据库操作Service实现
* @createDate 2024-10-09 17:03:06
*/
@Transactional
@Service
public class ErpUserServiceImpl extends ServiceImpl<ErpUserMapper, ErpUser>
    implements ErpUserService{
    
    @Resource
    private ErpOrganUserRelService erpOrganUserRelService;
    
    @Resource
    private ErpUserRoleService userRoleService;
    
    @Resource
    private ErpTenantService tenantService;
    
    @Resource
    private ErpRoleService roleService;
    
    public List<ErpUser> selectUser(){
        return this.baseMapper.selectUser();
    }
    
    @Override
    public IPage<ErpUserVO> queryUserPage(UserQuery userQuery) {
        Page<ErpUserVO> page = new Page<>(userQuery.getCurrent(), userQuery.getSize());
        
        return baseMapper.queryUserPage(page, userQuery);
    }
    
    @Override
    public boolean saveUser(UserParameter userParameter) {
        try {
            ErpUser erpUser = BeanUtil.copyProperties(userParameter, ErpUser.class);
            boolean save = save(erpUser);
            if (save){
                // 如果机构id不为空
                if (ObjectUtil.isNotEmpty(userParameter.getOrganId())){
                    ErpOrganUserRel rel = BeanUtil.copyProperties(userParameter, ErpOrganUserRel.class);
                    rel.setUserId(erpUser.getId());
                    rel.setCreateTime(new Date());
                    rel.setUpdateTime(new Date());
                    erpOrganUserRelService.save(rel);
                }
                return userRoleService.save(new ErpUserRole(erpUser.getId(), userParameter.getRoleId()));
            }else {
                // 手动回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }
    
    @Override
    public boolean updateUser(UserParameter userParameter) {
        try{
            ErpUser erpUser = BeanUtil.copyProperties(userParameter, ErpUser.class);
            // 修改用户信息
            boolean updateUser = updateById(erpUser);
            if (updateUser){
                // 如果机构id不为空
                if (ObjectUtil.isNotEmpty(userParameter.getOrganId())){
                    // 1.查询机构用户关系表该列是否存在
                    QueryWrapper<ErpOrganUserRel> wrapper = new QueryWrapper<>();
                    wrapper.lambda().eq(ErpOrganUserRel::getUserId, erpUser.getId())
                            .eq(ErpOrganUserRel::getTenantId, userParameter.getTenantId());
                    ErpOrganUserRel one = erpOrganUserRelService.getOne(wrapper);
                    // 2.如果存在
                    if (ObjectUtil.isNotEmpty(one)){
                        one.setUpdateTime(new Date());
                        one.setOrganId(userParameter.getOrganId());
                        one.setUpdater(userParameter.getUpdater());
                        erpOrganUserRelService.updateById(one);
                    } else {
                        ErpOrganUserRel rel = new ErpOrganUserRel(userParameter.getOrganId(), erpUser.getId(),
                                new Date(), userParameter.getCreator(), new Date(), userParameter.getUpdater(), userParameter.getTenantId());
                        erpOrganUserRelService.save(rel);
                    }
                } else{
                    // 机构id为空，删除列
                    LambdaUpdateWrapper<ErpOrganUserRel> wrapper = new LambdaUpdateWrapper<>();
                    wrapper.eq(ErpOrganUserRel::getUserId, erpUser.getId())
                            .eq(ErpOrganUserRel::getTenantId, userParameter.getTenantId());
                    erpOrganUserRelService.remove(wrapper);
                }
                
                LambdaUpdateWrapper<ErpUserRole> wrapper = new LambdaUpdateWrapper<>();
                wrapper.set(ErpUserRole::getRoleId, userParameter.getRoleId())
                        .eq(ErpUserRole::getUserId, erpUser.getId());
                userRoleService.update(wrapper);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }
    
    @Override
    public boolean resetPass(Long userId) {
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        LambdaUpdateWrapper<ErpUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(ErpUser::getPassword, bc.encode("123456"))
                .eq(ErpUser::getId, userId);
        return update(wrapper);
    }
    
    @Override
    public Result<String> updateUserStatus(List<String> userLoginNames, String loginName, Integer status) {
        userLoginNames.remove(loginName);
        if (CollUtil.isEmpty(userLoginNames)) return Result.error("抱歉，不能修改租户状态！");
        boolean update = lambdaUpdate()
                .in(ErpUser::getLoginName, userLoginNames)
                .set(ErpUser::getStatus, status)
                .update();
        return update ? Result.success("修改成功！") : Result.error("修改失败");
    }
    
    @Override
    public Result<String> removeBatchByLoginNames(List<String> userLoginNames, Long tenantId) {
        List<ErpUserVO> users = baseMapper.queryUserByTenant();
        for (ErpUserVO user : users) {
            if (userLoginNames.contains(user.getLoginName())) return Result.error("抱歉，租户不能删除！");
        }
        boolean remove = lambdaUpdate().in(ErpUser::getLoginName, userLoginNames)
                .eq(ErpUser::getTenantId, tenantId)
                .remove();
        return  remove ? Result.success("删除成功！") : Result.error("删除失败");
    }
    
    @Override
    public List<ErpUser> findUserByTenantId(Long tenantId) {
        return lambdaQuery().eq(ErpUser::getTenantId, tenantId)
                .list();
    }
    
    @Override
    public Boolean getUserCountByUserName(ErpUser user) {
        // 判断用户名是否重复
        Long count = lambdaQuery().eq(ErpUser::getLoginName, user.getUsername()).count();
        return count <= 0;
    }
    
    @Override
    public String userRegister(ErpUser user) {
        user.setLoginName(user.getUsername());
        // 密码加盐
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        // 新增用户
        boolean userSave = save(user);
        if (userSave){
            // 获取当前时间
            Date createDate = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(createDate);
            calendar.add(Calendar.YEAR, 10);
            Date tenYearsLater = calendar.getTime();
            
            ErpTenant tenant = new ErpTenant(user.getId(), user.getLoginName(), 2000, "1", 1, createDate, tenYearsLater);
            // 新增租户
            boolean tenantSave = tenantService.save(tenant);
            if (tenantSave){
                // 给用户赋值tenantId
                boolean update = lambdaUpdate().set(ErpUser::getTenantId, tenant.getId()).eq(ErpUser::getId, user.getId()).update();
                if (update){
                    LambdaQueryWrapper<ErpRole> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(ErpRole::getName, "租户");
                    ErpRole role = roleService.getOne(wrapper);
                    userRoleService.save(new ErpUserRole(user.getId(), role.getId()));
                    return user.getLoginName();
                }
            }
        }
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return "";
        
    }
}




